define(function(){

    var View = {
        baseUrl:  ""// "http://172.16.6.55:8082" //
    };
    //
    View.teamData = function(result,type){
        var scope = this;
        if(type=="order"){
            getTransit(result.nodeDataArray,result.linkRel,result.linkOrderRel);
        }
        //
        var nodes = [];
        var _fzRel = result.fzRel;
        var _links = result.linkRel;
        var _nodes = result.nodeDataArray;
        Array.prototype.push.apply(nodes,_nodes);
        //
        scope.nodes = _nodes;
        scope.type = type || "all";
        scope.links = _links;
        scope.data = {
            linkFromPortIdProperty:"fromPort",
            linkToPortIdProperty:"toPort",
            linkDataArray:result.linkDataArray,
            nodeDataArray:dataFilter()
        }
        return scope;

        function dataFilter(){
            var res = [];
            var nodesGroup = {};
            for(var i = nodes.length - 1;i > -1;i--){
                var one = nodes[i];
                delete one.child;
                clearNode(one);
                if(["start","end"].indexOf(one.category)>-1){
                    res.push(one);
                    nodes.splice(i,1);
                }else if(one.category){
                    one.text = one.key;// 展示名称
                    one.zOrder = 0;// 上下位置
                    one.child = [];// 内部元素
                    //
                    one.datas = nodesGroup[one.key] || (nodesGroup[one.key] = []);
                    res.push(one);
                    nodes.splice(i,1);
                }else{
                    nodesGroup[one.group] || (nodesGroup[one.group] = []);
                    nodesGroup[one.group].push(one);
                    View.addOccupyFlag(one);
                    View.addOccupyText(one);
                }
            }
            //
            res.forEach(function(group){
                if(group.category!="Process"){return;}//|| group.key!="裁剪组2"
                //
                View.setSubtext(group,nodes);
                var first = dataGroupFirst(group);
                if(first){
                    dataGroupItem(group,first);
                }
                dataGroupNouse(group);
            });
            return res;
        }

        function dataGroupFirst(group){
            var res, firstArr = [], nodeArr = group.datas;
            nodeArr.forEach(function(v,i) {
                if (v.group == group.key && ["1", "3"].indexOf(v.isWhere) > -1)
                    firstArr.push(i);
            });
            if(firstArr.length==1){
                res = nodeArr.splice(firstArr[0],1)[0];
                res.key_pre = res.key;
                View.addOccupyText(res);
            }else if(firstArr.length>1){
                var node = nodeArr[firstArr[0]];
                var link = _links.filter(function(vv){return vv.to== node.key;});
                if(link.length>0){
                    res = {key: "_"+link[0].from, text:"",group:group.key,category:""};
                }
            }
            return res;
        }

        function dataGroupItem(group,node){
            var nodeArr = group.datas;
            if(!node){
                return;
            }else if(node.group != group.key){// 末端
                nodeArr.push(node);
                return;
            }
            group.child.push(node);
            //
            var nowKey = dataFzFilter(group,node) || node.key;// 如果分组:定义分组子节点为起始点
            var multiLink = _links.filter(function(v){
                if(v.from == nowKey){
                    var next = View.getOne(nodeArr,{key:v.to});
                    if(next && next.group==group.key){
                        return v;
                    }
                }
            });
            if(multiLink.length==1){
                var link = multiLink[0];
                View.addOccupyText(node);
                var next = View.getOne(nodeArr,{key:link.to},true);
                View.addOccupyText(next,node.key);
                dataGroupItem(group,next);
                return false;
            }else if(multiLink.length>1){
                console.log("下级线:",multiLink);
                return true;
            }else{
                return true;
            }
        }

        function dataFzFilter(group,node){
            var nodeArr = group.datas;
            var obj = _fzRel[node.key];
            if(obj){
                var nextNode = node;
                var allArr = [], indexArr = [];
                //
                if(!/^\_/.test(node.key)){
                    nextNode = {key:"_"+node.key,text:""};
                    group.child.push(nextNode);
                }
                nextNode.child = [];
                for(var key in obj){
                    var arr = obj[key];
                    var childOne = {key:"_"+key,child:[]};
                    //console.log(key);
                    arr.forEach(function(v,i){
                        var nodeOne = View.getOne(nodeArr,{key:v},true);
                        if(!nodeOne){
                            //console.warn("node-分支:",v+"未找到");
                            return;
                        }
                        View.addOccupyText(nodeOne);
                        childOne.child.push(nodeOne);
                    })
                    nextNode.child.push(childOne);
                    //
                    indexArr.push(arr.pop());
                    Array.prototype.push.apply(allArr,arr);
                }
                //
                return View.gatewayNextKey(allArr,indexArr);
            }
            return;
        }

        function dataGroupNouse(group){
            var nodesArr = group.datas;
            nodesArr.forEach(function(v){
                if(v.group==group.key){
                    v.isNouse = 1;
                    group.child.splice(0,0,v);
                }
            });
        }

        function clearNode(node){
            if(!node.isGroup){
                if(["ParallelGateway","ExclusiveGateway"].indexOf(node.category)>-1){
                    node.gateway = node.category;
                    node.category = "";
                }else if(node.category=="Process"){
                    node.category = "";
                }
            }else{
                node.category = "Process";
            }
            node.isNouse = "";
            !node.pos && (node.pos = "");
            delete node.isGroup;
            //node.isGroup = "";
        }
    }

    View.setSubtext = function(group){
        var nodes = this.nodes;
        var links = this.links;
        var haslinks, key_pre, key_next;
        nodes.map(function(v){
            if(v.group == group.key){
                if(v.key == "163"){
                    key_pre = "653";
                    return;
                }
                // pre
                if(key_pre !== "" && ["1",'3'].indexOf(v.isWhere)>-1){
                    haslinks = links.filter(function(vv){return vv.to== v.key;});
                    if(haslinks.length==1){
                        key_pre = haslinks[0].from;
                    }else{
                        key_pre = "";
                    }
                }
                // next
                if(key_next !== "" && ["2",'3'].indexOf(v.isWhere)>-1){
                    haslinks = links.filter(function(vv){return vv.from== v.key;});
                    if(haslinks.length==1){
                        key_next = haslinks[0].to;
                    }else{
                        key_next = "";
                    }
                }
            }
        });
        //
        key_pre && (group.subtext = View.getOne(nodes,{key:key_pre}).text);
        key_next && (group.subtext1 = View.getOne(nodes,{key:key_next}).text);
    }

    View.addOccupyText = function(node,prekey){
        if(!node){return;}
        var nodes = this.nodes;
        var links = this.links;
        var key = {all:"occupy",order:"transit"}[this.type];
        if(!node.occupy_pre){
            var prelinks = links.filter(function(v){
                if(prekey){
                    return v.to==node.key && v.from==prekey;
                }else{
                    return v.to==node.key;
                }
            });
            var prelink = prelinks.length==1?prelinks[0]:'';
            if(prelink){
                node.occupy_pre = prelink[key];
                node.occupy_pre_valid = prelink.occupy_valid;
            }
        }
        if(!node.occupy_next){
            var nextlinks = links.filter(function(v){return v.from==node.key});
            var nextlink = nextlinks.length==1 ? nextlinks[0] : '';
            if(nextlink){
                node.occupy_next = nextlink[key];
                node.occupy_next_valid = nextlink.occupy_valid;
            }
        }
    }

    View.addOccupyFlag = function(node){
        if(!node){return;}
        var nodes = this.nodes;
        var links = this.links;
        // showOccupyPre
        if(["1","3"].indexOf(node.isWhere)>-1){
            node.showOccupyPre = "1";
        }
        if(node.gateway){
            var arr = links.filter(function(link){return link.from == node.key});
            arr.forEach(function(one){
                var nextNode = View.getOne(nodes,{key:one.to});
                nextNode && (nextNode.showOccupyPre = "1");
            });
        }
    }

    View.gatewayNextKey = function(allArr,indexArr){
        var key;
        indexArr.every(function(v){
            return allArr.indexOf(v)>-1 || !(key = v);// 从indexArr取出不在allArr中的一个值
        });
        return key;
    }

    View.getOne = function(arr,match,flag){
        var one;
        arr.every(function(v,i){
            var isThis = true;
            for(var key in match){
                if(match[key]!=v[key]){
                    isThis = false;
                }
            }
            if(isThis){
                one = v;
                flag && (arr.splice(i,1));
            }
            return !isThis;
        });
        return one;
    }

    View.teamLinkIcon = function(){
        var nodes = this.nodes;
        var links = JSON.stringify(this.data.linkDataArray);
        setPorts(nodes);
        function setPorts(arr){
            arr && arr.forEach(function(v) {
                var has = [];
                if(links.indexOf("\""+v.key+"_R\"")>-1){
                    has.push("R");
                }
                if(links.indexOf("\""+v.key+"_L\"")>-1){
                    has.push("L");
                }
                if(links.indexOf("\""+v.key+"_T\"")>-1){
                    has.push("T");
                }
                if(links.indexOf("\""+v.key+"_B\"")>-1){
                    has.push("B");
                }
                v.ports = has;
                if(v.child){
                    setPorts(v.child);
                }
            })
        }
        return this;
    }

    View.search = function(){
        var res = location.search.substr(1).replace(/=/g,"\":\"").replace(/&/g,"\",\"");
        return res?JSON.parse("{\""+res+"\"}"):{};
    }

    View.WebSocket = function(callback){
        var ws = View.ws;
        if(!ws){
            ws = new WebSocket("ws://" + View.baseUrl.replace(/.*\/\//,"") + "/websocket");
        }
        ws.onopen = callback.onopen || function(){
            View.ws = ws;
            //
            var search = View.search();
            ws.send(search.version);
        };

        ws.onmessage = callback.onmessage || function (evt){
            var received_msg = evt.data;
            //console.log("success",received_msg);
        };

        ws.onclose = callback.onclose || function(){
            View.ws = null;
        };
    }


    function getTransit(nodeDataArray,linkRel,linkOrderRel){
        var link;
        linkOrderRel.forEach(function(v){
            link = View.getOne(linkRel,{from:v.from,to:v.to});
            if(link){
                link.transit = v.transit;
            }else{
                var arr = linkRel.filter(function(vv){return vv.from== v.from;});
                if(arr.length==1){
                    arr[0].transit = v.transit;
                }
            }
        });
    }


    //
    window.View = View;
})